var express = require("express");
var app = express();
var mongoose = require("mongoose");
app.use(express.static("static"));

mongoose.connect("mongodb://127.0.0.1/todolists");
var star = require("./models/star.js").star;

app.get("/", function(req, res) {
    res.send("welcome to my world");
})
app.listen(9000);
console.log("开始运行服务器");

var getData = function(req, res, finish) {

    var page = req.query.page;
    var pageCount = req.query.pageCount;
    // console.log(pageCount); 
    var queryObj = {};
    if (finish) {
        queryObj = { finish: finish };
    }
    star.count(queryObj, function(err, docs) {
        var length = docs;
        var nowTotalPage = Math.ceil(length / pageCount);
        if (page >= nowTotalPage) {
            page = nowTotalPage - 1;
        }
        if (length <= 0) {
            res.send({
                status: 0,
                length: 0,
                totalPage: 1,
                page: 0,
            });
        } else {
            var skip = page * pageCount;
            star.find(queryObj, null, { skip: skip, limit: pageCount }, function(err, docs) {
                res.send({
                    status: 0,
                    length: length,
                    totalPage: nowTotalPage,
                    page: page,
                    data: docs
                });
            })
        }
    })
}
app.get("/del", function(req, res) {
    var id = req.query.id;
    console.log(id);
    star.remove({ _id: id }, function(err) {
        getData(req, res, );
    })
})
app.get("/gettodolistData", function(req, res) {
    var finish = "未完成";
    getData(req, res, finish);
})
app.get("/finishData", function(req, res) {
    var finish = "完成";
    getData(req, res, finish);
})

app.get("/add", function(req, res) {
    var newTodolist = req.query.newTodolist;
    star.create(newTodolist, function(err) {
        getData(req, res);
    })
})